// miniprogram/pages/editView/signUp/newWeiActivity.js
let network = require('../../../utils/requestManager.js')
let util = require('../../../utils/util.js')
let WxNotificationCenter = require("../../../utils/WxNotificationCenter.js");
let app = getApp()
const date = new Date()
const years = []
const months = []
const days = []
const hours = []
const seconds = []

const end_date = new Date()
const end_years = []
const end_months = []
const end_days = []
const end_hours = []
const end_seconds = []

//开始时间
for (let i = 1990; i <= date.getFullYear() + 1; i++) {
  years.push(i)
  end_years.push(i)
}

for (let i = 1; i <= 12; i++) {
  if(i < 10){
    i = "0" + i
  }
  months.push(""+i)
  end_months.push(""+i)
}

for (let i = 1; i <= 31; i++) {
  if(i < 10){
    i = "0" + i
  }
  days.push("" + i)
  end_days.push("" + i)
}

for (let i = 1; i <= 23; i++) {
  if(i < 10){
    i = "0" + i
  }
  hours.push("" + i)
  end_hours.push("" + i)
}

for (let i = 1; i <= 59; i++) {
  if(i < 10){
    i = "0" + i
  }
  seconds.push("" + i)
  end_seconds.push("" + i)
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    icon_banner:true,
    icon_activity_name:true,
    icon_activity_money:true,
    icon_activity_people:true,
    icon_init_people:true,
    icon_start_time:true,
    icon_end_time:true,
    icon_activity_desc:true,
    mask:false,
    years: years,
    // years: date.getFullYear() + 1,
    year: date.getFullYear(),
    months: months,
    month: date.getMonth() + 1,
    days: days,
    day: date.getDate(),
    hours: hours,
    hour: date.getHours(),
    seconds: seconds,
    second: date.getMinutes(),
    value: [date.getFullYear() - 1990, date.getMonth(), date.getDate() - 1, date.getHours() - 1, date.getMinutes() - 1],
    show_date: false,
    //end time
    end_years: end_years,
    end_year: date.getFullYear(),
    end_months: end_months,
    end_month: date.getMonth() + 1,
    end_days: end_days,
    end_day: date.getDate() + 1,
    end_hours: end_hours,
    end_hour: date.getHours(),
    end_seconds: end_seconds,
    end_second: date.getMinutes(),
    end_value: [date.getFullYear() - 1990, date.getMonth(), date.getDate(), date.getHours(), date.getMinutes()],
    end_show_date: false,
    banner:"",
    descList: [{
      type: 'image',
      imagePath: '',
      imageName: '',
      text: '',
      first: true
    }],
    title:"",
    price:"",
    limit_number:"",
    desc:"",
    wei_activity_id : "",
    hidden_textarea:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    let that = this;
    let ActivityId = options.activity_id
    if (ActivityId == undefined || ActivityId == "") {//创建
      ActivityId = ""
    } else {//编辑
      network.getRequest('apply/little/apply/product/detail', {id:ActivityId}, function (res) {
        console.log(res)
        
        let activity_detail = res.detail.product;

        //分割开始时间
        let strat_time = util.formatUTCDate(activity_detail.start_time)
        console.log(strat_time)
        strat_time = strat_time.replace(/ /g, '-')
        strat_time = strat_time.replace(/:/g, '-')
        let splitArray = new Array();
        splitArray = strat_time.split(/-/);//得到时间数组
        console.log(splitArray)

        //分割结束时间
        let end_time = util.formatUTCDate(activity_detail.end_time)
        end_time = end_time.replace(/ /g, '-')
        end_time = end_time.replace(/:/g, '-')
        let end_splitArray = new Array();
        end_splitArray = end_time.split(/-/);//得到时间数组
        console.log(end_splitArray)
        
        that.setData({
          wei_activity_id:ActivityId,
          banner: activity_detail.image_url,
          title:activity_detail.title,
          price: activity_detail.price / 100,
          limit_number: activity_detail.limit_number,
          begin_number: activity_detail.apply_people_number,
          desc: activity_detail.desc,
          descList: generateDescListByList(activity_detail.detail_product_url),
          year:splitArray[0],
          month:splitArray[1],
          day: splitArray[2],
          hour: splitArray[3],
          second: splitArray[4],

          end_year: end_splitArray[0],
          end_month: end_splitArray[1],
          end_day: end_splitArray[2],
          end_hour: end_splitArray[3],
          end_second: end_splitArray[4],
          icon_banner:false,
          icon_activity_name:false,
          icon_activity_money:false,
          icon_activity_people:false,
          icon_init_people:false,
          icon_start_time:false,
          icon_end_time:false,
          icon_activity_desc:false
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 上传活动图片
   * **/
  upload_img:function(e){
    let that = this;
    wx.chooseImage({
      count:1,
      // sizeType:"compressed",//压缩
      // sourceType:"album",//相册
      success: function(res) {
        console.log(res)
        var tempFilePaths = res.tempFilePaths
        var imagePath = tempFilePaths[0]
        wx.showLoading({
          title: '图片上传中...',
        })
        //上传图片请求
        network.uploadimg({
          path: tempFilePaths,
          finished: function (uploadRes) {
            wx.hideLoading()
            console.log(uploadRes)
            //拼接域名 + 图片名字
            that.setData({
              banner: uploadRes.images[0],
              icon_banner:false
            })
          }
        })
      },
      fail:function(){
        wx.showModal({
          title: '错误提示',
          content: '上传图片失败',
          showCancel: false,
          success: function (res) { }
        }) 
      }
    })
  },

  /**
   * 活动名称失去焦点
   * **/
  activity_name_out:function(e){
    let that = this;
    let activity_name = e.detail.value;
    if(activity_name ==="" || activity_name === null || activity_name === "undefined"){
      that.setData({
        icon_activity_name:true
      })
    }else{
      that.setData({
        icon_activity_name: false
      })
    }
  },

  /**
   * 活动费用失去焦点
   * **/
  activity_money_out:function(e){
    let that = this;
    let activity_inp_val = e.detail.value;
    if (activity_inp_val === "" || activity_inp_val === null || activity_inp_val === "undefined") {
      that.setData({
        icon_activity_money: true
      })
    } else {
      that.setData({
        icon_activity_money: false
      })
    }
  },

  /**
   * 限量人数失去焦点
   * **/
  activity_people_out: function (e) {
    let that = this;
    let activity_inp_val = e.detail.value;
    if (activity_inp_val === "" || activity_inp_val === null || activity_inp_val === "undefined") {
      that.setData({
        icon_activity_people: true
      })
    } else {
      that.setData({
        icon_activity_people: false
      })
    }
  },

  /**
   * 初始人数失去焦点
   * **/
  activity_init_out: function (e) {
    let that = this;
    let activity_inp_val = e.detail.value;
    if (activity_inp_val === "" || activity_inp_val === null || activity_inp_val === "undefined") {
      that.setData({
        icon_init_people: true
      })
    } else {
      that.setData({
        icon_init_people: false
      })
    }
  },

  /**
   * 活动简介失去焦点
   * **/
  activity_desc_out: function (e) {
    let that = this;
    let activity_inp_val = e.detail.value;
    if (activity_inp_val === "" || activity_inp_val === null || activity_inp_val === "undefined") {
      that.setData({
        icon_activity_desc: true
      })
    } else {
      that.setData({
        icon_activity_desc: false
      })
    }
  },

  /**
   * 开始日期picker
   * **/
  bindChange: function(e) {
    console.log(e)
    const val = e.detail.value
    this.setData({
      year: this.data.years[val[0]],
      month: this.data.months[val[1]],
      day: this.data.days[val[2]],
      hour: this.data.hours[val[3]],
      second: this.data.seconds[val[4]],
      value: [val[0], val[1], val[2], val[3], val[4]]
    })
  },

  /**
   * 结束日期picker
   * **/
  end_bindChange: function (e) {
    const val = e.detail.value
    console.log(val)
    this.setData({
      end_year: this.data.end_years[val[0]],
      end_month: this.data.end_months[val[1]],
      end_day: this.data.end_days[val[2]],
      end_hour: this.data.end_hours[val[3]],
      end_second: this.data.end_seconds[val[4]],
      end_value: [val[0], val[1], val[2], val[3], val[4]]
    })
  },

  /**
   * 点击开始时间显示picker
   * **/
  show_start_picker: function() {
    let that = this;
    let show_status = that.data.show_date;
    console.log(show_status)
    if (show_status == true) {
      console.log("hide")
      that.setData({
        show_date: false,
        mask: false,
        hidden_textarea:false//把textarea隐藏
      })
    } else {
      console.log("show")
      that.setData({
        show_date: true,
        mask: true,
        hidden_textarea: true//把textarea显示
      })
    }
  },

  /**
   * 结束时间：点击时间显示picker
   * **/
  end_show_start_picker: function () {
    let that = this;
    let show_status = that.data.end_show_date;
    console.log(show_status)
    if (show_status == true) {
      console.log("hide")
      that.setData({
        end_show_date: false,
        mask: false,
        hidden_textarea: true//把textarea隐藏
      })
    } else {
      console.log("show")
      that.setData({
        end_show_date: true,
        mask: true,
        hidden_textarea: true//把textarea显示
      })
    }
  },

  /**
   * 点击关闭picker
   * **/
  close_picker: function() {
    let that = this;
    that.setData({
      show_date: false,
      mask: false,
      icon_start_time: false,
      hidden_textarea:false//显示textarea
    })
  },

  /**
  * 结束时间：点击关闭picker
  * **/
  end_close_picker: function () {
    let that = this;
    that.setData({
      end_show_date: false,
      mask: false,
      icon_end_time:false,
      hidden_textarea: false//显示textarea
    })
  },

  //富文本内容修改响应
  contentDidChanged(e) {
    let list = e.detail.list
    console.log(e)
    this.setData({
      descList: list
    })
  },

  /**
   * 提交活动信息
   * **/
  activity_submit:function(eve){
    submit_activity_edit(this,eve)
  },


})

/**
 * 创建
 * 提交活动信息函数
 * e.detail.value为gorm表单所有value
 * **/
function submit_activity_edit(that,eve){
  let params = network.defaultParams()//获取的店铺信息
  let form_values = eve.detail.value
  console.log(form_values)
  let form_data = {}
  console.log(eve)
  if (form_values.image == "") {//判断活动图片
    wx.showToast({
      title: '请上传活动图片！',
      icon:"none"
    })
    return
  }
  form_data["image"] = form_values.image

  if (form_values.title == "") {//判断活动名称
    wx.showToast({
      title: '请填写活动名称！',
      icon: "none"
    })
    return
  }
  form_data["title"] = form_values.title

  if (form_values.price == "") {//判断活动费用
    wx.showToast({
      title: '请填写活动费用！',
      icon: "none"
    })
    return
  }
  form_data["price"] = form_values.price*100

  if (form_values.limit_number == "") {//判断限量人数
    wx.showToast({
      title: '请填写限量人数！',
      icon: "none"
    })
    return
  }
  form_data["limit_number"] = form_values.limit_number

  if (form_values.begin_number == "") {//判断初始人数
    wx.showToast({
      title: '请填写初始人数！',
      icon: "none"
    })
    return
  }

  //限量人数,初始人数
  let parse_limit_number = parseFloat(form_values.limit_number)
  //限量人数
  let parse_begin_number = parseFloat(form_values.begin_number)

  //初始人数不能大于限量人数
  if (parse_limit_number < parse_begin_number) {
    wx.showToast({
      title: '初始人数不能大于限量人数',
      icon:"none"
    })
    return
  }
  form_data["begin_number"] = form_values.begin_number

  //开始时间和结束时间
  form_data["start_time"] = form_values.start_time
  form_data["end_time"] = form_values.end_time
  if (form_values.desc == "") {//判断活动简介
    wx.showToast({
      title: '请填写活动简介！',
      icon: "none"
    })
    return
  }
  form_data["desc"] = form_values.desc

  //活动详情

  if (generateDescList(that.data.descList, that) == "image") {
    wx.showToast({
      title: '带图片详情描述需要上传一张图片！',
      icon: "none"
    })
    return
  }
  if (generateDescList(that.data.descList, that) == "text") {
    wx.showToast({
      title: '请输入纯文字描述的内容！',
      icon: "none"
    })
    return
  }

  form_data["detail_product"] = JSON.stringify(generateDescList(that.data.descList, that))
  console.log(form_data["detail_product"])
  form_data["product_id"] = that.data.wei_activity_id
  
  console.log(that.data.descList)
  console.log(form_data)

  let shop_id = network.shopParams().shop_id
  form_data["shop_id"] = shop_id
  //post请求提交
  network.postRequest('apply/little/apply/product/create', { form_data }, function (res) {
    console.log(res)
    console.log("token"+app.globalData.token)
    if(res.status == 0){
      //提交成功跳转微报名列表，传参
      wx.redirectTo({
        // url: '/pages/index/index?currentTab=' + 1,
        url: '/pages/editView/personalCenter/activityManage',
      })
    }else{
      wx.showToast({
        title: res.detail,
        icon:"none"
      })
    }
  })
};

/**
 * 过滤富文本编辑的图片和文字
 * 转化为数组
 * **/
function generateDescList(array, that) {
  var tempArr = []
  var typeStr = ""
  for (var i = 0; i < array.length; i++) {
    var item = array[i]
    ///图片类型，图片必选
    if (item.type == 'image' && item.imageName == '') {
      typeStr = "image"
      break
    }
    ///文本类型，文本必填
    if (item.type == 'text' && item.text == "") {
      typeStr = "text"
      break
    }
    tempArr.push({
      image: item.imageName,
      content: item.text
    })
  }
  return typeStr == "" ? tempArr : typeStr
}

///根据请求到的详情描述数组生成可用的数据
function generateDescListByList(array) {
  var temp = []
  if (array.length == 0) {
    temp.push({
      type: 'image',
      imagePath: '',
      imageName: '',
      text: '',
      first: true
    })
  } else {
    for (var i = 0; i < array.length; i++) {
      var item = array[i]
      var descItem = {
        type: item.image != "" && item.image != undefined ? "image" : "text",
        imagePath: item.image,
        imageName: item.image,
        text: item.content,
        first: i == 0 ? true : false,
        last: i == array.length - 1 ? true : false
      }
      temp.push(descItem)
    }
  }
  console.log(temp)
  return temp
}